package com.example.petshop.controller;

import com.example.petshop.entity.Address;
import com.example.petshop.entity.User;
import com.example.petshop.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @GetMapping("/details/{addressid}")
    public Address getAddressDetails(@PathVariable int addressid) {
        System.out.println(addressid);
        return addressService.getAddressById(addressid);
    }
    @PostMapping("/save")
    public ResponseEntity<Address> updateAddress(@RequestBody Address address) {

        Address updatedAddress = addressService.updateAddress(address);
        System.out.println("21312");
        return ResponseEntity.ok(updatedAddress);
    }
    @GetMapping("/getaddress")
    public ResponseEntity<List<Address>> getAddress(HttpServletRequest request) {
        // 从Session中获取已登录的用户信息
        HttpSession session = request.getSession(false); // false表示不创建新Session
        if (session != null) {
            User loggedInUser = (User) session.getAttribute("loggedInUser");
            if (loggedInUser != null) {
                // 获取用户的user_id
                Long userId = loggedInUser.getUserId();

                // 根据userId查询Address表中的地址信息
                List<Address> addresses = addressService.getAddressesByUserId(userId);
                if (!addresses.isEmpty()) {
                    return ResponseEntity.ok(addresses);
                } else {
                    return ResponseEntity.notFound().build();
                }
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }
    @PostMapping("/add")
    public Address addAddress(@RequestBody Address address, HttpServletRequest request){
        HttpSession session = request.getSession(true);
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        Long userId = loggedInUser.getUserId();
        String nickName = loggedInUser.getNickName();
        address.setUserId(userId);
        address.setNickName(nickName);
        return addressService.addAddress(address);
    }
    @DeleteMapping("/deleteAddress/{addressid}")
    public ResponseEntity<String>  deleteAddress(@PathVariable int addressid) {
        System.out.println("要删除的addressid  " +addressid);
        boolean result = addressService.removeById(addressid);
        if (result) {
            return ResponseEntity.ok("删除地址成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("删除地址失败，未找到对应地址");
        }
    }

    @PostMapping("/setdefault/{addressid}")
    public ResponseEntity<Address> setDefaultAddress(@PathVariable int addressid, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            User loggedInUser = (User) session.getAttribute("loggedInUser");
            if (loggedInUser != null) {
                try {
                    Address defaultAddress = addressService.setAsDefaultAddress(addressid, loggedInUser.getUserId());
                    if (defaultAddress != null) {
                        return ResponseEntity.ok(defaultAddress);
                    } else {
                        return ResponseEntity.notFound().build();
                    }
                } catch (Exception e) {
                    // Log the exception
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
                }
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }
    @GetMapping("/getdefaultaddress")
    public ResponseEntity<?> getDefaultAddress(HttpServletRequest request){
        HttpSession session = request.getSession(false); // false表示不创建新Session
        if (session != null) {
            User loggedInUser = (User) session.getAttribute("loggedInUser");
            if (loggedInUser != null) {
                Long userId = loggedInUser.getUserId();
                Address defaultAddress = addressService.getDefaultAddressByUserId(userId);
                if (defaultAddress != null) {
                    return ResponseEntity.ok(defaultAddress);
                } else {
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body("没有找到默认地址");
                }
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

}
